package com.df.happylearn.articlecontent;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.df.happylearn.R;
import com.df.happylearn.activity.BaseActivity;
import com.df.happylearn.model.ArticleContentInfo;
import com.df.happylearn.utils.Constants;
import com.df.happylearn.utils.CssUtil;

/**
 * Created by dingfeng on 2016/5/24.
 */
public class ContentActivity extends BaseActivity implements ContentContract.View {

    private final static String TAG = ContentActivity.class.getSimpleName();

    AppBarLayout mAppBarLayout;
    CollapsingToolbarLayout collapsingToolbar;
    Toolbar mToolbar;
    ProgressBar progressBar;
    WebView mWebView;
    View no_network_ui;
    TextView txtReferesh;

    private int articleId;
    private String articleContent;
    private ContentContract.Presenter mContentPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_content);
        Intent intent = getIntent();
        articleId = intent.getIntExtra("articleId", -1);
        if (articleId < 0) {
            return;
        }
        mContentPresenter = new ContentPresenter(this, articleId);
        initView();
        initData();
    }

    private void initView() {
        mAppBarLayout = (AppBarLayout) findViewById(R.id.appbarlayout);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setNavigationIcon(R.drawable.back_img);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle("");
        collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 添加js交互接口类，并起别名 imagelistner
        mWebView.addJavascriptInterface(new MyJavascriptInterface(this), "imagelistner");
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(webChromeClient);

        no_network_ui = findViewById(R.id.no_network_ui);
        no_network_ui.setVisibility(View.GONE);
        txtReferesh = (TextView) findViewById(R.id.txtReferesh);
        txtReferesh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContentPresenter.loadArticleContent();
            }
        });
    }

    private void initData() {
        mContentPresenter.start();
    }

    @Override
    public void setPresenter(ContentContract.Presenter presenter) {
        mContentPresenter = presenter;
    }

    @Override
    public void showContent(ArticleContentInfo contentInfo) {
        hideNoNetworkView();
        loadArticle(contentInfo);
    }

    @Override
    public void showLoadError() {
        showNoNetworkView();
        hideProgressBar();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("article_id", articleId);
        setResult(Constants.ACTICLEACTIVITY_RESULT_CODE, intent);
        super.onBackPressed();
    }

    private void loadArticle(ArticleContentInfo bean) {
        if (bean.mTitle.contains("_")) {
            String[] aa = bean.mTitle.split("_");
            articleContent = "<div class=time>" + aa[1] + " 浏览次数:" + bean.mViews + "</div>" + bean.mContent;
            mWebView.loadData(CssUtil.getInstance().injectCss(articleContent), "text/html; charset=UTF-8", null);
            setToolbarTitle(aa[0]);
        } else {
            articleContent = "<div class=time>" + "Crazy studio" + " 浏览次数:" + bean.mViews + "</div>" + bean.mContent;
            mWebView.loadData(CssUtil.getInstance().injectCss(articleContent), "text/html; charset=UTF-8", null);
            setToolbarTitle(bean.mTitle);
        }
    }

    private void setToolbarTitle(String title) {
        collapsingToolbar.setTitle(title);
    }

    private void showNoNetworkView() {
        no_network_ui.setVisibility(View.VISIBLE);
        mWebView.setVisibility(View.GONE);
    }

    private void hideNoNetworkView() {
        no_network_ui.setVisibility(View.GONE);
        mWebView.setVisibility(View.VISIBLE);
    }

    private void hideProgressBar() {
        progressBar.setVisibility(View.INVISIBLE);
    }

    private void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
    }

    WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
            if (newProgress == 100) {
                hideProgressBar();
            } else {
                showProgressBar();
            }
            super.onProgressChanged(view, newProgress);
        }
    };

    // 遍历所有的img几点，并添加onclick函数，函数的功能是在图片点击的时候调用本地java接口并传递url过去
    String JAVASCRIPT_FUNCTION = "javascript:(function(){" +
            "var objs = document.getElementsByTagName(\"img\"); " +
            "var urls = new Array;" +
            "for(var i=0;i<objs.length;i++)  " +
            "{" +
            "urls[i] = objs[i].src;" +
            "    objs[i].onclick=function()  " +
            "    {  " +
            "        window.imagelistner.openImage(urls.toString(), this.src);  " +
            "    }  " +
            "}" +
            "})()";

    private void addImageClickListner() {
        mWebView.loadUrl(JAVASCRIPT_FUNCTION);
    }

    // js通信接口
    public class MyJavascriptInterface {

        private Context context;

        public MyJavascriptInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openImage(String urls, String currentUrl) {
            Intent intent = new Intent();
            intent.putExtra("images", urls);
            intent.putExtra("current", currentUrl);
            intent.setClass(context, ShowWebImageActivity.class);
            context.startActivity(intent);
        }
    }

    // 监听
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListner();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

    }
}
